const finance = require('../../../utils/finance')
const app = getApp()

Page({
  data: {
    splitId: '', // 拆分ID
    splitRecords: [], // 拆分后的记录列表
    loading: false,
    refreshing: false,
  },

  onLoad(options) {
    if (options.splitId) {
      this.setData({ splitId: options.splitId });
      this.loadSplitRecords();
    } else {
      wx.showToast({ title: '缺少拆分ID参数', icon: 'none' });
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
    }
  },

  /**
   * 加载拆分记录
   */
  async loadSplitRecords() {
    if (this.data.loading) return;
    
    this.setData({ loading: true });
    
    try {
      // 调用拆分结果接口
      const res = await finance.splitResult(this.data.splitId);
      
      if (res && Array.isArray(res)) {

        // res.data为数组
        const recordList = (res || []).map(item => ({
          id: item.id || item.accountBookId, // 若无id则用accountBookId
          type: item.financeType, // 'expense' or 'income'
          category: item.categoryName,
          categoryCode: item.categoryCode,
          financeDesc: item.financeDesc || '',
          amount: item.totalAmount,
          paymentMethod: item.paymentMethod,
          financeDate: item.financeDate,
          financeTime: item.financeTime,
          details: [],
          expanded: false,
          userName: item.userName
        }));

        this.setData({
          splitRecords: recordList,
          loading: false
        });
      } else {
        this.setData({
          splitRecords: [],
          loading: false
        });
        wx.showToast({ title: '获取拆分记录失败', icon: 'none' });
      }
    } catch (e) {
      console.error('加载拆分记录失败:', e);
      this.setData({ loading: false });
      wx.showToast({ title: '加载失败', icon: 'none' });
    }
  },

  /**
   * 删除记录
   */
  onDeleteRecord(e) {
    // 重新加载记录列表
    this.loadSplitRecords();
  },

  /**
   * 下拉刷新
   */
  async onPullDownRefresh() {
    this.setData({ refreshing: true });
    await this.loadSplitRecords();
    wx.stopPullDownRefresh();
    this.setData({ refreshing: false });
  },

  /**
   * 返回列表页面
   */
  goBackToList() {
    wx.navigateBack();
  },

  /**
   * 返回财务首页
   */
  goToFinanceIndex() {
    wx.redirectTo({
      url: '/pages/finance/index/index'
    });
  },

  /**
   * 页面显示
   */
  onShow() {
    // 页面显示时可以刷新数据
    if (this.data.splitId) {
      this.loadSplitRecords();
    }
  }
}); 